package com.bkhc.partner.service;

import com.alibaba.fastjson.JSONObject;
import com.bkhc.common.constant.RoleContant;
import com.bkhc.common.entity.Lookup;
import com.bkhc.common.entity.User;
import com.bkhc.common.entity.UserRole;
import com.bkhc.common.enu.BrandStatusEnum;
import com.bkhc.common.repository.LookupRepository;
import com.bkhc.common.repository.UmcRepository;
import com.bkhc.common.repository.UserRepository;
import com.bkhc.common.repository.UserRoleRepository;
import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.response.PageUtil;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.UserBean;
import com.bkhc.partner.bo.PriceSchame;
import com.bkhc.partner.entity.Employee;
import com.bkhc.partner.entity.Partner;
import com.bkhc.partner.entity.PartnerBrand;
import com.bkhc.partner.repository.EmployeeRepository;
import com.bkhc.partner.repository.PartnerBrandRepository;
import com.bkhc.partner.repository.PartnerRepository;
import com.bkhc.partner.repository.ProductRepository;
import com.bkhc.partner.vo.BrandGoodPrice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PartnerSerivce {

    @Autowired
    private PartnerRepository partnerRepository;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UmcRepository umcRepository;
    @Autowired
    private UserRoleRepository userRoleRepository ;

    @Autowired
    private PartnerBrandRepository partnerBrandRepository ;

    public ResultJson<?> addPartner(Partner partner) {
        Partner old = partnerRepository.findByPartnerCode(partner.getPartnerCode());
        if(old!=null){
            partner.setId(old.getId());
        }
        partnerRepository.save(partner);
        employeeRepository.deleteAllByPartnerCode(partner.getPartnerCode());
        employeeRepository.save(partner.getEmployee());

//        partnerBrandRepository.deleteAllByPartnerCode(partner.getPartnerCode());
//        partnerBrandRepository.saveAll(partner.getPartnerBrands());

        String userId = partner.getEmployee().getUserId();
        UserRole userRoleOld = userRoleRepository.findByUserIdAndRoleCode(userId, RoleContant.PARTNER);
        if(userRoleOld!=null){
            ResultJson<?> resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        User u = umcRepository.findByUserId(userId);
        User uold = userRepository.findByUserId(userId);
        if(uold!=null){
            u.setId(uold.getId());
        }
        userRepository.save(u);
        UserRole userRole = new UserRole();
        userRole.setRoleCode(RoleContant.PARTNER);
        userRole.setUserId(userId);
        userRole.setStatus("1");
        userRoleRepository.save(userRole);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }
    public ResultJson<?> deletePartner(String partnerCode) {
        partnerRepository.deleteByPartnerCode(partnerCode);
        Employee employ = employeeRepository.findByPartnerCode(partnerCode);
        employeeRepository.deleteAllByPartnerCode(partnerCode);
        userRepository.deleteByUserId(employ.getUserId());
        userRoleRepository.deleteByUserId(employ.getUserId());
        return ResultJson.success();
    }
    public Partner getPartnerByUser(String userId) {
        Employee e = employeeRepository.findByUserId(userId);
        if(e == null){
            return null;
        }
        Partner partner = partnerRepository.findByPartnerCode(e.getPartnerCode());
        return partner;
    }

    public ResultJson<?> getBrandProduct(int pageIndex,int pageSize) {
        String jsonstr = (String) CommonUtil.getDataScope();
        Partner partner = JSONObject.parseObject(jsonstr, Partner.class);
        PartnerBrand partnerBrand = new PartnerBrand();
        partnerBrand.setPartnerCode(partner.getPartnerCode());
//        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
//        PageRequest pageRequest = PageRequest.of(pageIndex-1, pageSize, Sort.by(orders));
//        Page<PartnerBrand> page = null;
//        page = partnerBrandRepository.findAll(partnerBrand, pageRequest);
//        PageUtil pageUtil = new PageUtil(page);
        ResultJson resultJson=productRepository.queryBrandProductByPartner(pageIndex,pageSize,partner.getPartnerCode());
        return  resultJson;
    }

    public ResultJson<?> queryProductByBrand(String brandCode) {

        String jsonstr = (String) CommonUtil.getDataScope();
        Map partner = JSONObject.parseObject(jsonstr, Map.class);
       return productRepository.queryProductByBrand(brandCode,partner.get("partnerCode").toString());
    }

    public ResultJson<?> getProductSpec(String productCode) {
        return productRepository.getProductSpec(productCode);
    }

    public ResultJson<?> getBrandProductGood(String productCode, String brandCode) {
        return productRepository.getBrandProductGood(productCode,brandCode);
    }

    public ResultJson<?> getUploadPriceRule(String productCode, String brandCode) {
        return productRepository.getUploadPriceRule(productCode,brandCode);
    }

    public ResultJson<?> queryUploadPrice(String productCode, String brandCode) {
        return productRepository.queryUploadPrice(productCode,brandCode);
    }
    public ResultJson<?> getProduct(String productCode) {
        return productRepository.getProduct(productCode);
    }
    public ResultJson<?> getBrand(String brandCode) {
        return productRepository.getBrand(brandCode);
    }

    public List<String> getHead(Map<String,Object> product,String brandCode) {
        List<Map<String,String>> priceRule = (List<Map<String,String>> ) productRepository.getUploadPriceRule(product.get("productCode").toString(),brandCode).getData();
        List<String> head = new ArrayList<>();
        head.add("品牌");
        head.add("产品");
        List<Map<String,String>> speclist = (List) product.get("productSpecList");
         for(Map<String,String> spec:speclist){
             head.add(spec.get("specName"));
         }
        for(Map<String,String> price:priceRule){
            head.add(price.get("indentityName"));
        }
        return head;
    }

    public List<Map<String,Object>> getData(String productCode, String brandCode) {
        List<Map<String,Object>> brandProductGoods = (List<Map<String,Object>>)productRepository.getBrandProductGood(productCode, brandCode).getData();
        return brandProductGoods;
    }

    public void parsePrice(List<List<String>> result, String brandCode, String productCode) {
        List<BrandGoodPrice> response = new ArrayList<>();
        List<String> head = null;
        List<List<String>> data = new ArrayList<>();
        for(int i=0;i<result.size();i++){
            if(i==0){
                head = result.get(i);
            }else{
                data.add(result.get(i));
            }
        }
        List<Map<String,String>> priceMap = new ArrayList<>();
        for(List<String> price:data){
            Map<String,String> map = new HashMap<>();
            for(int index=0;index<price.size();index++){
                if(index<head.size()){
                    map.put(head.get(index).toString(),price.get(index).toString());
                }

            }
            priceMap.add(map);
        }
        List<Map<String,String>> priceRule = (List<Map<String,String>> ) productRepository.getUploadPriceRule(productCode,brandCode).getData();
        UserBean u = CommonUtil.getCrruentUser();
        List<Map<String,Object>> goodslist = (List<Map<String, Object>>) productRepository.getBrandProductGood(productCode, brandCode).getData();
        for(Map<String,String> price:priceMap){
                for(Map<String,Object> goods:goodslist){
                    boolean flag = true;
                    List<Map<String,String>> goodspecs = (List<Map<String,String>>) goods.get("goodsSpecList");
                    for(Map<String,String> spec:goodspecs){
                        if(!price.get(spec.get("specName")).equals(spec.get("specValue"))){
                            flag = false;
                            break;
                        }
                    }
                    if(flag == true) {
                        for (Map<String, String> rule : priceRule) {
                            BrandGoodPrice bgp = new BrandGoodPrice();
                            bgp.setProductCode(productCode);
                            bgp.setBrandCode(brandCode);
                            bgp.setGoodsCode(goods.get("goodsCode").toString());
                            bgp.setIndentity(rule.get("indentity"));
                            bgp.setPrice(new BigDecimal(Double.parseDouble(price.get(rule.get("indentityName")))));
                            bgp.setStatus("1");
                            bgp.setCreator(u.getUserId());
                            bgp.setUpdator(u.getUserId());
                            response.add(bgp);
                        }
                    }
                }
        }
        productRepository.uploadPrice(response);
    }


}
